import React, { Component } from 'react';
import { Row, Col, Icon, Tooltip, Tabs, Card, Carousel } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import CountUp from 'react-countup';
import classNames from 'classnames';
import styles from './Analysis.less';
import { ChartCard, MiniArea, MiniBar, MiniProgress, Field } from '@/components/Charts';
import Gauge from './Guide';
import Trend from '@/components/Trend';
import numeral from 'numeral';
import Yuan from '@/utils/Yuan';

const { TabPane } = Tabs;
class IntroduceRow extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cusActiveKey: '0',
      cargoActiveKey: '0',
      receiptActiveKey: '0',
      balanceActiveKey: '0',
      dots: false,
      autoplay: false,
      autoplaySpeed: 1000 * 60 * 10 + 100,
    };
    this.cusCarouselRef = React.createRef();
    this.cargoCarouselRef = React.createRef();
    this.receiptCarouselRef = React.createRef();
    this.balanceCarouselRef = React.createRef();

    this.cusTabPanes = [
      { title: '客户数', key: '0' },
      { title: '今日', key: '1' },
      { title: '昨日', key: '2' },
    ];
    this.cargoTabPanes = [
      { title: '货量', key: '0' },
      { title: '今日', key: '1' },
      { title: '昨日', key: '2' },
    ];
    this.receiptTabPanes = [
      { title: '销售额', key: '0' },
      { title: '今日', key: '1' },
      { title: '昨日', key: '2' },
    ];
    this.balanceTabPanes = [
      { title: '余额', key: '0' },
      { title: '今日', key: '1' },
      { title: '昨日', key: '2' },
    ];

    this.countUpProps = {
      duration: 4,
      separator: ',',
      delay: 0,
    };

    this.countUpDecProps = {
      duration: 5,
      separator: ',',
      decimals: 2,
      decimal: '.',
      delay: 0,
    };

    this.countUpKgProps = {
      duration: 6,
      separator: ',',
      decimals: 3,
      decimal: '.',
      delay: 0,
    };
    this.unit = [
      // 金额到达亿则以万元为单位
      {
        numLenth: 8,
        divideNum: 10000,
      },
      // 重量、件数、单数超过亿则以千为单位
      {
        numLenth: 8,
        divideNum: 1000,
      },
    ];
  }

  unitConvert = (num, maxLength, unit, isWeight) => {
    let newNum = num;
    const numArr = (num + '').split('.');
    const isConvert = numArr[0].length > maxLength;
    if (isConvert) {
      newNum = num / unit;
    }
    if (numArr[1]) {
      newNum = isWeight ? newNum.toFixed(3) : newNum.toFixed(2);
    }
    return {
      isConvert,
      newNum,
    };
  };

  handleCusTabsChange = key => {
    this.setState({
      cusActiveKey: key,
    });
    this.cusCarouselRef.current.slick.slickGoTo(key - 0);
  };
  handleCusBeforeChange = (from, to) => {
    this.setState({
      cusActiveKey: to + '',
    });
  };

  handleReceiptTabsChange = key => {
    this.setState({
      receiptActiveKey: key,
    });
    this.receiptCarouselRef.current.slick.slickGoTo(key - 0);
  };
  handleReceiptBeforeChange = (from, to) => {
    this.setState({
      receiptActiveKey: to + '',
    });
  };

  handleBalanceTabsChange = key => {
    this.setState({
      balanceActiveKey: key,
    });
    this.balanceCarouselRef.current.slick.slickGoTo(key - 0);
  };
  handleBalanceBeforeChange = (from, to) => {
    this.setState({
      balanceActiveKey: to + '',
    });
  };

  handleCargoTabsChange = key => {
    this.setState({
      cargoActiveKey: key,
    });
    this.cargoCarouselRef.current.slick.slickGoTo(key - 0);
  };
  handleCargoBeforeChange = (from, to) => {
    this.setState({
      cargoActiveKey: to + '',
    });
  };

  formatterCurrency = money => {
    return `${numeral(money).format('0,000.00')} 元`;
  };

  refreshVal = val => {
    if (val - 0 === 0) {
      return val;
    }
    if (val === null) val = '';
    const array = val.toString().split('.');
    let decimalDigits = 0;
    if (array[1]) {
      decimalDigits = array[1].length + 1;
    } else {
      decimalDigits = 1;
    }
    const randomNum = Math.random() / Math.pow(10, decimalDigits);
    return Number(val) + Number(randomNum);
  };

  renderCusGauge = customer => {
    const { isConvert, newNum } = this.unitConvert(
      customer.customerNum,
      this.unit[1].numLenth,
      this.unit[1].divideNum
    );
    const { isConvert: isConvert2, newNum: newNum2 } = this.unitConvert(
      customer.enterpriseNum,
      this.unit[1].numLenth,
      this.unit[1].divideNum
    );
    const countUpProps = isConvert ? this.countUpDecProps : this.countUpProps;
    const countUpProps2 = isConvert2 ? this.countUpDecProps : this.countUpProps;

    const newEnd = this.refreshVal(newNum);
    const newEnd2 = this.refreshVal(newNum2);
    return (
      <div style={{ position: 'relative' }}>
        <Gauge height={100} maxValue={customer.customerNum} currentValue={customer.enterpriseNum} />
        <Tooltip
          title={() => {
            return (
              <>
                <div>
                  总客户：
                  {numeral(customer.customerNum).format('0,000')} 位
                </div>
                <div>
                  企业客户：
                  {numeral(customer.enterpriseNum).format('0,000')} 位
                </div>
              </>
            );
          }}
        >
          <div style={{ position: 'absolute', top: '32%', width: '100%', textAlign: 'center' }}>
            <div style={{ fontSize: 30, fontWeight: 600, color: '#FFD83A' }}>
              <CountUp {...countUpProps} start={0} end={newEnd || 0} />
              <span style={{ fontSize: 14, opacity: '0.55', color: '#FFD83A' }}>
                <span>{isConvert2 ? '千位' : '位'}</span>
              </span>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#FFFF' }}>
              <span style={{ fontSize: 14, opacity: '0.55', marginRight: '1%' }}>企业</span>
              <CountUp {...countUpProps2} start={0} end={newEnd2 || 0} />
              <span style={{ fontSize: 14, opacity: '0.55', marginLeft: '1%', color: '#FFFF' }}>
                <span>{isConvert2 ? '千位' : '位'}</span>
              </span>
            </div>
          </div>
        </Tooltip>
      </div>
    );
  };

  renderTotalCustomer = () => {
    const { cusActiveKey, dots, autoplay, autoplaySpeed } = this.state;
    const {
      loading,
      visitData: { customers },
    } = this.props;

    const totalCus = {
      total: {
        customerNum: customers && customers.total && customers.total.customerNum,
        enterpriseNum: customers && customers.total && customers.total.enterpriseNum,
      },

      yesterday: {
        customerNum: customers && customers.yesterday && customers.yesterday.customerNum,
        enterpriseNum: customers && customers.yesterday && customers.yesterday.enterpriseNum,
      },
      today: {
        customerNum: customers && customers.today && customers.today.customerNum,
        enterpriseNum: customers && customers.today && customers.today.enterpriseNum,
      },
    };
    const settings = {
      dots,
      autoplay,
      autoplaySpeed,
    };
    const introduce = () => {
      return (
        <div>
          <div>客户数：累计客户数，其中分为个人客户和企业客户</div>
          <div>今日：今日新增客户数，其中分为个人客户和企业客户</div>
          <div>昨日：昨日新增客户数，其中分为个人客户和企业客户</div>
        </div>
      );
    };
    return (
      <>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Tabs
            activeKey={cusActiveKey}
            onChange={this.handleCusTabsChange}
            style={{
              width: '92%',
            }}
            className={styles.cargoTabs}
          >
            {this.cusTabPanes.map((item, i) => {
              return <TabPane tab={item.title} key={item.key} />;
            })}
          </Tabs>
          <Tooltip title={introduce()}>
            <Icon
              type="info-circle-o"
              style={{ lineHeight: '50px', fontSize: 20, color: 'rgba(255, 255, 255, 0.6)' }}
            />
          </Tooltip>
        </div>
        <Carousel {...settings} beforeChange={this.handleCusBeforeChange} ref={this.cusCarouselRef}>
          <div>{this.renderCusGauge(totalCus.total)}</div>
          <div>{this.renderCusGauge(totalCus.today)}</div>
          <div>{this.renderCusGauge(totalCus.yesterday)}</div>
        </Carousel>
      </>
    );
  };

  renderReceiptDetail = receipt => {
    const { isConvert, newNum } = this.unitConvert(
      receipt,
      this.unit[0].numLenth,
      this.unit[0].divideNum
    );
    const newEnd = this.refreshVal(newNum);
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
        }}
        className={styles.introduceTop}
      >
        <Tooltip title={this.formatterCurrency(receipt)}>
          <span
            style={{ color: '#000', fontWeight: 600, overflowX: 'auto', color: '#FF6E4B' }}
            className={classNames(styles.adaptationFontSize, { [styles.moneyScroll]: true })}
          >
            <CountUp {...this.countUpDecProps} start={0} end={newEnd || 0} />
          </span>
        </Tooltip>
        <span
          style={{ opacity: '0.85', marginLeft: 4, color: '#FF6E4B' }}
          className={styles.suffixFontSize}
        >
          {isConvert ? '万' : '元'}
        </span>
      </div>
    );
  };

  renderTotalReceipt = () => {
    const { receiptActiveKey, dots, autoplay, autoplaySpeed } = this.state;
    const {
      loading,
      visitData: { receipt },
    } = this.props;
    const totalReceipt = {
      total: receipt && receipt.total,
      today: receipt && receipt.today,
      yesterday: receipt && receipt.yesterday,
    };
    const settings = {
      dots,
      autoplay,
      autoplaySpeed,
    };
    const introduce = () => {
      return (
        <div>
          <div>销售额：账户总收款金额</div>
          <div>今日：账户今日新增收款金额</div>
          <div>昨日：账户昨日新增收款金额</div>
        </div>
      );
    };
    return (
      <>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Tabs
            activeKey={receiptActiveKey}
            onChange={this.handleReceiptTabsChange}
            style={{
              width: '92%',
            }}
            className={styles.cargoTabs}
          >
            {this.receiptTabPanes.map((item, i) => {
              return <TabPane tab={item.title} key={item.key} />;
            })}
          </Tabs>
          <Tooltip title={introduce()}>
            <Icon
              type="info-circle-o"
              style={{ lineHeight: '50px', fontSize: 20, color: 'rgba(255, 255, 255, 0.6)' }}
            />
          </Tooltip>
        </div>
        <Carousel
          {...settings}
          beforeChange={this.handleReceiptBeforeChange}
          ref={this.receiptCarouselRef}
        >
          <div>{this.renderReceiptDetail(totalReceipt.total)}</div>
          <div>{this.renderReceiptDetail(totalReceipt.today)}</div>
          <div>{this.renderReceiptDetail(totalReceipt.yesterday)}</div>
        </Carousel>
      </>
    );
  };

  renderReceiptBalance = balance => {
    const { isConvert, newNum } = this.unitConvert(
      balance,
      this.unit[0].numLenth,
      this.unit[0].divideNum
    );
    const newEnd = this.refreshVal(newNum);
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
        }}
        className={styles.introduceTop}
      >
        <Tooltip title={this.formatterCurrency(balance)}>
          <span
            style={{ color: '#000', fontWeight: 600, overflowX: 'auto', color: '#33EC8B' }}
            className={classNames(styles.adaptationFontSize, { [styles.moneyScroll]: true })}
          >
            <CountUp {...this.countUpDecProps} start={0} end={newEnd || 0} />
          </span>
        </Tooltip>
        <span
          style={{ opacity: '0.85', marginLeft: 4, color: '#33EC8B' }}
          className={styles.suffixFontSize}
        >
          {isConvert ? '万' : '元'}
        </span>
      </div>
    );
  };

  renderTotalBalance = () => {
    const { balanceActiveKey, dots, autoplay, autoplaySpeed } = this.state;
    const {
      loading,
      visitData: { balances },
    } = this.props;
    const totalBalances = {
      yesterday: balances && balances.yesterday,
      today: balances && balances.today,
      total: balances && balances.total,
    };
    const settings = {
      dots,
      autoplay,
      autoplaySpeed,
    };
    const introduce = () => {
      return (
        <div>
          <div>余额：账户总余额</div>
          <div>今日：账户今日新增充值金额</div>
          <div>昨日：账户昨日新增充值金额</div>
        </div>
      );
    };
    return (
      <>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Tabs
            activeKey={balanceActiveKey}
            onChange={this.handleBalanceTabsChange}
            style={{
              width: '92%',
            }}
            className={styles.cargoTabs}
          >
            {this.balanceTabPanes.map((item, i) => {
              return <TabPane tab={item.title} key={item.key} />;
            })}
          </Tabs>
          <Tooltip title={introduce()}>
            <Icon
              type="info-circle-o"
              style={{ lineHeight: '50px', fontSize: 20, color: 'rgba(255, 255, 255, 0.6)' }}
            />
          </Tooltip>
        </div>

        <Carousel
          {...settings}
          beforeChange={this.handleBalanceBeforeChange}
          ref={this.balanceCarouselRef}
        >
          <div>{this.renderReceiptBalance(totalBalances.total)}</div>
          <div>{this.renderReceiptBalance(totalBalances.today)}</div>
          <div>{this.renderReceiptBalance(totalBalances.yesterday)}</div>
        </Carousel>
      </>
    );
  };

  renderCargoDetail = cargoVolumes => {
    const { isConvert, newNum } = this.unitConvert(
      cargoVolumes.weightTotal,
      this.unit[1].numLenth,
      this.unit[1].divideNum,
      true
    );
    const { isConvert: isConvert2, newNum: newNum2 } = this.unitConvert(
      cargoVolumes.packageNumTotal,
      this.unit[1].numLenth,
      this.unit[1].divideNum
    );
    const { isConvert: isConvert3, newNum: newNum3 } = this.unitConvert(
      cargoVolumes.orderNum,
      this.unit[1].numLenth,
      this.unit[1].divideNum
    );
    const countUpProps2 = isConvert2 ? this.countUpDecProps : this.countUpProps;
    const countUpProps3 = isConvert3 ? this.countUpDecProps : this.countUpProps;

    const newEnd = this.refreshVal(newNum);
    const newEnd2 = this.refreshVal(newNum2);
    const newEnd3 = this.refreshVal(newNum3);

    return (
      <div
        style={{
          display: 'flex',
          height: 112,
          justifyContent: 'space-around',
          flexDirection: 'column',
          marginLeft: 20,
        }}
      >
        <div style={{ textAlign: 'end' }}>
          <Tooltip title={`${numeral(cargoVolumes.weightTotal).format('0,000.000')} kg`}>
            <span style={{ color: '#5FF2FF', fontSize: 27, fontWeight: 600 }}>
              <CountUp {...this.countUpKgProps} start={0} end={newEnd || 0.0} />
            </span>
            <span style={{ opacity: '0.85', marginLeft: 4, fontSize: 14, color: '#5FF2FF' }}>
              {isConvert ? 't' : 'kg'}
            </span>
          </Tooltip>
        </div>
        <div style={{ textAlign: 'end' }}>
          <Tooltip title={`${numeral(cargoVolumes.packageNumTotal).format('0,000')} 件`}>
            <span style={{ color: '#5FF2FF', fontSize: 27, fontWeight: 600 }}>
              <CountUp {...countUpProps2} start={0} end={newEnd2} />
            </span>
            <span style={{ opacity: '0.85', marginLeft: 4, fontSize: 14, color: '#5FF2FF' }}>
              {isConvert2 ? '千件' : '件'}
            </span>
          </Tooltip>
        </div>
        <div style={{ textAlign: 'end' }}>
          <Tooltip title={`${numeral(cargoVolumes.orderNum).format('0,000')} 单`}>
            <span style={{ color: '#5FF2FF', fontSize: 27, fontWeight: 600 }}>
              <CountUp {...countUpProps3} start={0} end={newEnd3 || 0} />
            </span>
            <span style={{ opacity: '0.85', marginLeft: 4, fontSize: 14, color: '#5FF2FF' }}>
              {isConvert3 ? '千单' : '单'}
            </span>
          </Tooltip>
        </div>
      </div>
    );
  };

  renderTotalCargoVol = () => {
    const { cargoActiveKey, dots, autoplay, autoplaySpeed } = this.state;
    const {
      loading,
      visitData: { cargoVolumes },
    } = this.props;
    const totalCargoVolume = {
      total: {
        weightTotal: cargoVolumes && cargoVolumes.total && cargoVolumes.total.weightTotal,
        weightUnit: cargoVolumes && cargoVolumes.total && cargoVolumes.total.weightUnit,
        packageNumTotal: cargoVolumes && cargoVolumes.total && cargoVolumes.total.packageNumTotal,
        orderNum: cargoVolumes && cargoVolumes.total && cargoVolumes.total.orderNum,
      },
      today: {
        weightTotal: cargoVolumes && cargoVolumes.today && cargoVolumes.today.weightTotal,
        weightUnit: cargoVolumes && cargoVolumes.today && cargoVolumes.today.weightUnit,
        packageNumTotal: cargoVolumes && cargoVolumes.today && cargoVolumes.today.packageNumTotal,
        orderNum: cargoVolumes && cargoVolumes.today && cargoVolumes.today.orderNum,
      },
      yesterday: {
        weightTotal: cargoVolumes && cargoVolumes.yesterday && cargoVolumes.yesterday.weightTotal,
        weightUnit: cargoVolumes && cargoVolumes.yesterday && cargoVolumes.yesterday.weightUnit,
        packageNumTotal:
          cargoVolumes && cargoVolumes.yesterday && cargoVolumes.yesterday.packageNumTotal,
        orderNum: cargoVolumes && cargoVolumes.yesterday && cargoVolumes.yesterday.orderNum,
      },
    };
    const settings = {
      dots,
      autoplay,
      autoplaySpeed,
    };
    const introduce = () => {
      return (
        <div>
          <div>
            货量：累计交货数量，公斤数为累计交货重量，件数为累计交货件数，订单数为累计下单笔数
          </div>
          <div>
            今日：今日交货数量，公斤数为今日交货重量，件数为今日交货件数，订单数为今日下单笔数
          </div>
          <div>
            昨日：昨日交货数量，公斤数为昨日交货重量，件数为昨日交货件数，订单数为昨日下单笔数
          </div>
        </div>
      );
    };
    return (
      <>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Tabs
            activeKey={cargoActiveKey}
            onChange={this.handleCargoTabsChange}
            style={{
              width: '92%',
            }}
            className={styles.cargoTabs}
          >
            {this.cargoTabPanes.map((item, i) => {
              return <TabPane tab={item.title} key={item.key} />;
            })}
          </Tabs>
          <Tooltip title={introduce()}>
            <Icon
              type="info-circle-o"
              style={{ lineHeight: '50px', fontSize: 20, color: 'rgba(255, 255, 255, 0.6)' }}
            />
          </Tooltip>
        </div>

        <Carousel
          {...settings}
          beforeChange={this.handleCargoBeforeChange}
          ref={this.cargoCarouselRef}
        >
          <div>{this.renderCargoDetail(totalCargoVolume.total)}</div>
          <div>{this.renderCargoDetail(totalCargoVolume.today)}</div>
          <div>{this.renderCargoDetail(totalCargoVolume.yesterday)}</div>
        </Carousel>
      </>
    );
  };

  render() {
    const {
      loading,
      visitData: { customers, balances, receipt },
    } = this.props;
    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 6,
      style: { marginBottom: 24 },
    };
    const totalCus = {
      customerNum: customers && customers.total && customers.total.customerNum,
      enterpriseNum: customers && customers.total && customers.total.enterpriseNum,
      yesterday: customers && customers.yesterday && customers.yesterday.customerNum,
      today: customers && customers.today && customers.today.customerNum,
    };

    return (
      <Row gutter={24}>
        <Col {...topColResponsiveProps}>
          <ChartCard
            loading={loading}
            bodyStyle={{
              padding: loading ? '20px 24px 8px 24px' : '0px 24px',
              borderRadius: 2,
            }}
            show="false"
            className={styles.receiptHeight}
          >
            {this.renderTotalCustomer()}
          </ChartCard>
        </Col>
        <Col {...topColResponsiveProps}>
          <ChartCard
            loading={loading}
            bodyStyle={{
              padding: loading ? '20px 24px 8px 24px' : '0px 24px',
              borderRadius: 2,
            }}
            show="false"
            className={styles.receiptHeight}
          >
            {this.renderTotalReceipt()}
          </ChartCard>
        </Col>
        <Col {...topColResponsiveProps}>
          <ChartCard
            loading={loading}
            bodyStyle={{
              padding: loading ? '20px 24px 8px 24px' : '0px 24px',
              borderRadius: 2,
            }}
            show="false"
            className={styles.receiptHeight}
          >
            {this.renderTotalBalance()}
          </ChartCard>
        </Col>
        <Col {...topColResponsiveProps}>
          <ChartCard
            loading={loading}
            bodyStyle={{
              padding: loading ? '20px 24px 8px 24px' : '0px 24px',
              borderRadius: 2,
            }}
            show="false"
            className={styles.receiptHeight}
          >
            {this.renderTotalCargoVol()}
          </ChartCard>
        </Col>
      </Row>
    );
  }
}

export default IntroduceRow;
